﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using ExamAnalysis.Model;
using ExamAnalysis.Core;
using System.IO;

namespace ExamAnalysis.Input
{
    public partial class InputStudentAnswers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ExamAnalysisDataContext db = new ExamAnalysisDataContext();
                var myExam = from eg in db.ExamInfo

                             select eg;
                this.Store1.DataSource = myExam;
                this.Store1.DataBind();

            }
        }
        protected void Button_Click(object sender, Ext.Net.DirectEventArgs e)
        {
            int examid = 0;
            RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                examid = Convert.ToInt32(row.RecordID);
            }
            string strPath = Server.MapPath("~/Input/ExcelTemplate/作答信息录入模版.xlsx");
            string sNewName = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ".xls";
            string toPath = Server.MapPath("~/Input/temp/" + sNewName);

            using (ExamAnalysisDataContext db = new ExamAnalysisDataContext())
            {
                var ls = from s in db.ExamItems
                         where s.ExamItemsGroup.ExamID == examid
                         select s;
                ExcelUtil.WriteExamItemsToExcel(ls.ToList(), new FileInfo(strPath), new FileInfo(toPath));
            }
            if (File.Exists(toPath))
            {
                FileStream fs = new FileStream(toPath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                Response.Charset = "UTF-8";
                Response.ContentType = "application/octet-stream";
                //通知浏览器下载文件而不是打开
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AddHeader("Content-Disposition", "attachment; filename=成绩登记表.xls");
                    //+ HttpUtility.UrlEncode("Grade.xls", System.Text.Encoding.UTF8));
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }

        }

        protected void RowSelect_ExamInfo(object sender, DirectEventArgs e)
        {
            ExamAnalysisDataContext db = new ExamAnalysisDataContext();
            int examId = 0;
            try
            {
                examId = int.Parse(e.ExtraParams["ExamID"]);
            }
            catch (FormatException ex)
            {
                return;
            }

            if (examId != -1)
            {
                var list = from s in db.StudentInExam
                           where s.ExamID == examId
                           select new { s.StudentID, s.ExamID, s.StudentInfo.StudentName };
                Store_StInExem.DataSource = list;
                Store_StInExem.DataBind();
            }
        }

        protected void uploadAnswer_DirectClick(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = this.GridPanel_StInExem.GetSelectionModel() as RowSelectionModel;
            int groupId = 0;
            if (sm.SelectedRows.Count != 0)
            {
                groupId = int.Parse(sm.SelectedRows[0].RecordID);
            }
            else
            {
                X.Msg.Alert("通知", "请选择学生！").Show();
            }
            string UploadFile = "";
            if (this.AnswerFile.HasFile)
            {
                UploadFile = this.AnswerFile.PostedFile.FileName.ToString();
                int FileSize = Int32.Parse(this.AnswerFile.PostedFile.ContentLength.ToString());
                if (FileSize > 5 * 1024 * 1024)
                {
                    X.Msg.Alert("提示信息", "上传文件过大！").Show();
                    return;
                }
                string strFileName = Path.GetExtension(this.AnswerFile.PostedFile.FileName).ToLower();//获取文件后缀
                if (!(strFileName == ".xls" || strFileName == ".xlsx"))
                {
                    X.Msg.Alert("提示信息", "文件格式不正确！").Show();
                    return;
                }

                Random ran = new Random();
                string sNewName = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100, 999)
                  + Path.GetExtension(this.AnswerFile.PostedFile.FileName);
                string strPath = Server.MapPath("~/FileUpload/" + sNewName);
                if (!Directory.Exists(Path.GetDirectoryName(strPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strPath));
                }
                this.AnswerFile.PostedFile.SaveAs(strPath);
                //
                FileInfo file = new FileInfo(strPath);
                X.Msg.Alert("提示信息", String.Format("成功添加{0}个题目的成绩", InputUtil.inputAnswersFromExcel(file, groupId))).Show();
                file.Delete();
            }
            else
            {
                X.Msg.Alert("通知", "请选择您需要上传的文件！").Show();
            }
        }
    }
}